<template>
	<s-layout title="选择地址">
		<view class="cicon-notice"
		      style="padding: 5px;
	          margin: 5px;
	          width: 95%;
	          background-color: #F39800;
	          border-radius: 10px; color: #FFFFFF;">
			<text>注意事项：</text>
			<br>
			<text>· 货物已经打包不可以更改路线</text>
			<br>
			<text>· 如果要拆除原包装的话，物品损坏由买家自行承担</text>
			<br>
			<text>
				·   必须付完款才可以发货</text>
			<br>
			<!--<text>
				<uni-tag class="sold-label ss-m-r-10 bg-red-gradient" text="直邮" :custom-style="sheep.$helper.tagCustomStyle()" size="small"></uni-tag>
				发货数量不超过
				<text class="number-waring">{{ state.expressLimit.zhi_count }}件</text>
			</text>-->
			<!--<br>
			<text>
				<uni-tag class="sold-label ss-m-r-10" text="拼邮" :custom-style="sheep.$helper.tagCustomStyle()" size="small"></uni-tag>
				书籍与CD不可以参与拼邮</text>
			<br>
			<text>
				<uni-tag class="sold-label ss-m-r-10" text="拼邮" :custom-style="sheep.$helper.tagCustomStyle()" size="small"></uni-tag>
				发货数量不超过
				<text class="number-waring">{{ state.expressLimit.pin_count }}件</text>
			</text>
			<br>
			<text>
				<uni-tag class="sold-label ss-m-r-10" text="拼邮" :custom-style="sheep.$helper.tagCustomStyle()" size="small"></uni-tag>
				商品总重不超过
				<text class="number-waring">{{ state.expressLimit.pin_weight }}g</text>
			</text>
			<br>
			<text>
				<uni-tag class="sold-label ss-m-r-10" text="拼邮" :custom-style="sheep.$helper.tagCustomStyle()" size="small"></uni-tag>
				最高单价不超过
				<text class="number-waring">{{ state.expressLimit.pin_item_price }}日元</text>
			</text>
			<br>
			<text>
				<uni-tag class="sold-label ss-m-r-10" text="拼邮" :custom-style="sheep.$helper.tagCustomStyle()" size="small"></uni-tag>
				商品总价不超过
				<text class="number-waring">{{ state.expressLimit.pin_sum_price }}日元</text>
			</text>
			<br>
			<text>
				<uni-tag class="sold-label ss-m-r-10" text="拼邮" :custom-style="sheep.$helper.tagCustomStyle()" size="small"></uni-tag>
				物品的长宽高不得超过15cm</text>
			<br>-->
		</view>
		<view
				class="bg-white address-box ss-m-b-14 ss-r-b-10"
				@tap="onSelectAddress"
		>
			<s-address-item :hasBorderBottom="false" :item="state.addressInfo">
				<view class="ss-rest-button">
					<text class="_icon-forward"></text>
				</view>
			</s-address-item>
		</view>
		<view class="order-card-box ss-m-b-14">
			<!--<s-goods-item
				v-for="item in state.orderInfo.skuList"
				:key="item.skuId"
				:img="item.pic"
				:title="item.productName"
				:skuText="item.productId"
				:price="item.price"
				:num="item.quantity"
				marginBottom="10"
			>
			</s-goods-item>-->

			<view class="order-item ss-flex ss-col-center ss-row-between ss-p-x-20 bg-white ss-r-10">
				<view class="item-title">邮寄方式</view>
				<view class="ss-flex ss-col-center">
					<!--<uni-easyinput
						maxlength="20"
						placeholder="填写包裹备注信息"
						v-model="state.orderPayload.remark"
						:inputBorder="false"
						:clearable="false"
					></uni-easyinput>-->
					<view class="item-value ss-m-r-24">
						{{ state.orderPayload.sendType == 0 ? '直邮-' + state.orderPayload.channelName : '拼邮' }}
					</view>
				</view>
			</view>

			<view class="order-item ss-flex ss-col-center ss-row-between ss-p-x-20 bg-white ss-r-10">
				<view class="item-title">发货数量</view>
				<view class="ss-flex ss-col-center">
					<view class="item-value ss-m-r-24">{{ state.expressInfo.count }}件</view>
				</view>
			</view>

			<view class="order-item ss-flex ss-col-center ss-row-between ss-p-x-20 bg-white ss-r-10">
				<view class="item-title">商品总重</view>
				<view class="ss-flex ss-col-center">
					<view class="item-value ss-m-r-24">{{ state.expressInfo.weight }}g</view>
				</view>
			</view>

			<view class="order-item ss-flex ss-col-center ss-row-between ss-p-x-20 bg-white ss-r-10">
				<view class="item-title">最高单价</view>
				<view class="ss-flex ss-col-center">
					<view class="item-value ss-m-r-24">{{ state.expressInfo.maxJpPrice }}日元</view>
				</view>
			</view>

			<view class="order-item ss-flex ss-col-center ss-row-between ss-p-x-20 bg-white ss-r-10">
				<view class="item-title">商品总价</view>
				<view class="ss-flex ss-col-center">
					<view class="item-value ss-m-r-24">{{ state.expressInfo.jpPrice }}日元</view>
				</view>
			</view>

			<view class="order-item ss-flex ss-col-center ss-row-between ss-p-x-20 bg-white ss-r-10">
				<view class="item-title">包裹备注</view>
				<view class="ss-flex ss-col-center">
					<uni-easyinput
							v-model="state.orderPayload.note"
							:clearable="false"
							:inputBorder="false"
							maxlength="20"
							placeholder="填写包裹备注信息"
					></uni-easyinput>
				</view>
			</view>

			<view style="position: relative; margin-top: 3%" v-if="state.showTable">
				<uni-table ref="table" border emptyText="暂无更多数据" stripe>
					<uni-tr>
						<uni-th align="center" width="220rpx">申报商品</uni-th>
						<uni-th align="center" width="80rpx">申报单价</uni-th>
						<uni-th align="center" width="80rpx">申报数量</uni-th>
					</uni-tr>
					<uni-tr v-for="(item, index) in state.tableData" :key="index">
						<uni-td>
							<uni-easyinput
									v-model="item.name"
									:inputBorder="false"
									placeholder="请填写申报商品名称"
							>
							</uni-easyinput>
						</uni-td>
						<uni-td>
							<uni-easyinput
									v-model="item.price"
									:inputBorder="false"
									placeholder="请填写申报商品单价"
									type="digit"
							>
								<template #right>
									日元
								</template>
							</uni-easyinput>
						</uni-td>
						<uni-td align="center">
							<uni-easyinput
									v-model="item.num"
									:inputBorder="false"
									placeholder="请填写申报商品数量"
									type="number"
							>
								<template #right>
									件
								</template>
							</uni-easyinput>
						</uni-td>
					</uni-tr>
				</uni-table>
			</view>


			<view v-if="!sheep.$helper.isRealEmpty(state.tableInfo[0])" style="margin-top: 3%; position: relative; background-color: #FFFFFF; padding: 15px">
				<mp-html :content="state.tableInfo[0].remark"></mp-html>
			</view>

		</view>
		<!-- 合计 -->
		<!--<view class="bg-white total-card-box ss-p-20 ss-m-b-14 ss-r-10">
			<view class="total-box-content border-bottom">
				<view class="order-item ss-flex ss-col-center ss-row-between">
					<view class="item-title">商品总金额</view>
					<view class="ss-flex ss-col-center">
						<text class="item-value ss-m-r-24">￥{{ state.orderInfo.productTotalAmount }}</text>
					</view>
				</view>
			</view>
			<view class="total-box-footer ss-font-28 ss-flex ss-row-right ss-col-center ss-m-r-28">
				<view class="total-num ss-m-r-20">共{{ state.totalNumber }}件</view>
				<view>合计：</view>
				<view class="total-num text-red"> ￥{{ state.orderInfo.orderTotalAmount }} </view>
				<view class="ss-flex" v-if="state.orderPayload.order_type == 'score'">
					<view class="total-num ss-font-30 text-red ss-m-l-4"> + </view>
					<image
						:src="sheep.$url.static('/static/img/shop/goods/score1.svg')"
						class="score-img"
					></image>
					<view class="total-num ss-font-30 text-red">{{ state.orderInfo.orderTotalAmount }}</view>
				</view>
			</view>
		</view>-->
		<!-- 底部 -->
		<su-fixed :index="200" :noFixed="false" :opacity="false" bg="bg-white" bottom placeholder>
			<view class="footer-box border-top ss-flex ss-row-between ss-p-x-20 ss-col-center">
				<!--<view class="total-box-footer ss-flex ss-col-center">
					<view class="total-num ss-font-30 text-red"> ￥{{ state.orderInfo.orderTotalAmount }} </view>
				</view>-->

				<!--<button
						v-if="state.orderPayload.sendType == 0"
						class="add-btn ss-reset-button ui-Shadow-Main"
						@tap="onConfirm(-3)"
				>
					开始收集
				</button>-->
				<button
						class="add-btn ss-reset-button ui-Shadow-Main"
						@tap="onConfirm(0)"
				>
					提交申请
				</button>
			</view>
		</su-fixed>
	</s-layout>
</template>

<script setup>
import {computed, reactive} from 'vue';
import {onLoad} from '@dcloudio/uni-app';
import sheep from '@/sheep';
import {isEmpty} from 'lodash';
import {tagCustomStyle} from "@/sheep/helper/utils";

const state = reactive({
	orderPayload: {},
	expressLimit: {},
	expressInfo: {},
	orderInfo: {},
	tableInfo: [],
	addressInfo: {},
	tableData: [],
	invoiceInfo: {},
	totalNumber: 0,
	showCoupon: false,
	showTable: true,
	couponInfo: [],
	showDiscount: false,
	sendTypeList: [
		{
			text: '直邮',
			value: 0,
		},
		{
			text: '拼邮',
			value: 1,
		}
	],
});

// 立即兑换(立即兑换无需跳转收银台)
const exchangeNow = computed(
		() => state.orderPayload.order_type == 'score' && state.orderInfo.pay_fee == 0,
);

//选择售后类型
function onRefundChange(e) {
	state.orderPayload.sendType = e.detail.value;
}

// 选择地址
function onSelectAddress() {
	uni.$once('SELECT_ADDRESS', (e) => {
		changeConsignee(e.addressInfo);
	});
	sheep.$router.go('/pages/user/address/list');
}

// 更改收货人地址&计算包裹信息
async function changeConsignee(addressInfo = {}) {
	if (isEmpty(addressInfo)) {
		const res = await sheep.$api.user.address.default();
		if (!isEmpty(res)) {
			addressInfo = res;
		}
	}
	if (!isEmpty(addressInfo)) {
		state.addressInfo = addressInfo;
		state.orderPayload.addressId = state.addressInfo.id;
	}
	// getOrderInfo();
}

// 选择优惠券
async function onSelectCoupon(e) {
	state.orderPayload.coupon_id = e || 0;
	getOrderInfo();
	state.showCoupon = false;
}

// 选择发票信息
function onSelectInvoice() {
	uni.$once('SELECT_INVOICE', (e) => {
		state.invoiceInfo = e.invoiceInfo;
		state.orderPayload.invoice_id = e.invoiceInfo.id || 0;
	});
	sheep.$router.go('/pages/user/invoice/list');
}

// 提交包裹/立即兑换
function onConfirm(status) {
	console.log('1111')
	if (!state.orderPayload.addressId && state.orderInfo.need_address == 1) {
		sheep.$helper.toast('请选择收货地址');
		return;
	}

	// 确认框
	uni.showModal({
		title: '提示',
		content: '发货时不带原包装，信封，纸箱之类的，不占重量！原包装重量不予参考！',
		success: async function (res) {
			if (res.confirm) {
				await submitOrder(status);
			} else {

			}
		}
	});

	// submitOrder(status);

	// submitOrder(status);
	// if (exchangeNow.value) {
	//   uni.showModal({
	//     title: '提示',
	//     content: '确定使用积分立即兑换?',
	//     cancelText: '再想想',
	//     success: async function (res) {
	//       if (res.confirm) {
	//         submitOrder();
	//       }
	//     },
	//   });
	// } else {
	// }
}

// 创建包裹&跳转
async function submitOrder(status) {
	let res = undefined
	state.orderPayload.tableInfo = state.tableData
	console.log(state.orderPayload)
	if (state.orderPayload.sendType == 0) {
		// 直邮
		state.orderPayload.status = status;
		res = await sheep.$api.order.batchConfirmSendTypeForm(state.orderPayload);
	} else if (state.orderPayload.sendType == 1) {
		// 拼邮
		res = await sheep.$api.order.batchConfirmSendType(
				state.orderPayload.selectOrderIds,
				state.orderPayload.sendType,
				state.orderPayload.addressId,
				state.orderPayload.targetExpressNo,
		);
	}
	if (res) {
		sheep.$helper.toast('确认邮寄方式成功, 耐心等待客服审核')
		// 返回订单列表
		sheep.$router.go("/pages/order/list", {type: '3'})
	}
	uni.getSetting({
		withSubscriptions: true,
		success(res) {
			console.log('1', res.subscriptionsSetting);
			if (!res.subscriptionsSetting.mainSwitch) {
				uni.openSetting({ //打开设置页
					success(res) {

					}
				})
			} else {
				uni.requestSubscribeMessage({
					tmplIds: ['ACfaSLxO5tVKYfFa-JK0tEvUiY-62R11ikQXrM2M36M'],
					success(res) {

					},
					fail(err) {

					}
				})
			}
		}
	})
}

// 检查库存&计算包裹价格
async function getOrderInfo() {
	const skuList = state.orderPayload.goods_list.map(it => {
		return {skuId: it.skuId, quantity: it.goods_num}
	})
	let res = await sheep.$api.order.calc({skuList});
	if (!res) {
		setTimeout(() => {
			sheep.$router.back()
		}, 2000)
		return
	}
	state.totalNumber = 0
	state.orderInfo = res
	state.orderInfo.skuList.forEach((item) => {
		let str = '默认规格'
		/*const obj = JSON.parse(item.spData)
		Object.keys(obj).forEach((key) => {
			str += key + ": " + obj[key] + "  "
		})*/
		item.spDataValue = str
		state.totalNumber += item.quantity
	})
}

// 获取可用优惠券
async function getCoupons() {
	const {error, data} = await sheep.$api.order.coupons(state.orderPayload);
	if (error == 0) {
		state.couponInfo = data;
	}
}

onLoad(async (options) => {
	if (options.data) {
		state.orderPayload = JSON.parse(options.data);
		console.log(state.orderPayload)
		changeConsignee();
		// 读取说明内容
		let tableInfo = await sheep.$api.order.channelList({type: 'channel_table'});
		state.tableInfo = tableInfo;
		// 初始化申报表格
		for (let i = 0; i < 4; i++) {
			let obj = {
				name: "",
				price: 0.00,
				num: 0
			}
			state.tableData.push(obj)
		}
		// 初始化检查发货信息渲染数据-限制字典
		let expressLimit = await sheep.$api.order.channelList({type: 'express_limit'});
		state.expressLimit = JSON.parse(expressLimit[0].dictValue)
		// 查询是否显示申报表格字段
		let tableShowDict =  await sheep.$api.dict.getDict('no_info_channel_id', 'value');
		if (tableShowDict) {
			state.showTable = !tableShowDict.data.includes(state.orderPayload.channelId)
			console.log(state.showTable, tableShowDict.data, state.orderPayload.channelId)
		}
		// 初始化检查发货信息渲染数据-真实的订单数据
		let res = undefined
		state.orderPayload.tableInfo = state.tableData
		console.log(state.orderPayload)
		if (state.orderPayload.sendType == 0) {
			// 直邮
			state.orderPayload.status = 0;
			res = await sheep.$api.order.queryBatchConfirmSendTypeForm(state.orderPayload);
		} else if (state.orderPayload.sendType == 1) {
			// 拼邮
			res = await sheep.$api.order.queryBatchConfirmSendType(
					state.orderPayload.selectOrderIds,
					state.orderPayload.sendType,
					state.orderPayload.addressId
			);
		}
		if (res) {
			console.log(res)
			state.expressInfo = res;
		}

		// if (state.orderPayload.order_type !== 'score') {
		//   getCoupons();
		// }
	}
});
</script>

<style lang="scss" scoped>
:deep() {
	.uni-input-wrapper {
		width: 320rpx;
	}

	.uni-easyinput__content-input {
		font-size: 28rpx;
		height: 72rpx;
		text-align: right !important;
		padding-right: 0 !important;

		.uni-input-input {
			font-weight: 500;
			color: #333333;
			font-size: 26rpx;
			height: 32rpx;
			margin-top: 4rpx;
		}
	}

	.uni-easyinput__content {
		display: flex !important;
		align-items: center !important;
		justify-content: right !important;
	}
}

.score-img {
	width: 36rpx;
	height: 36rpx;
	margin: 0 4rpx;
}

.order-item {
	height: 80rpx;

	.item-title {
		font-size: 28rpx;
		font-weight: 400;
	}

	.item-value {
		font-size: 28rpx;
		font-weight: 500;
	}

	.item-value {
		font-family: OPPOSANS;
	}

	.text-disabled {
		color: #bbbbbb;
	}

	.item-icon {
		color: $dark-9;
	}

	.remark-input {
		text-align: right;
	}

	.item-placeholder {
		color: $dark-9;
		font-size: 26rpx;
		text-align: right;
	}
}

.total-box-footer {
	height: 90rpx;

	.total-num {
		color: #333333;
		font-family: OPPOSANS;
	}
}

.footer-box {
	height: 100rpx;

	.submit-btn {
		width: 240rpx;
		height: 70rpx;
		font-size: 28rpx;
		font-weight: 500;

		.goto-pay-text {
			line-height: 28rpx;
		}
	}

	.cancel-btn {
		width: 240rpx;
		height: 80rpx;
		font-size: 26rpx;
		background-color: #e5e5e5;
		color: $dark-9;
	}
}

.title {
	font-size: 36rpx;
	font-weight: bold;
	color: #333333;
}

.subtitle {
	font-size: 28rpx;
	color: #999999;
}

.cicon-checkbox {
	font-size: 36rpx;
	color: var(--ui-BG-Main);
}

.cicon-box {
	font-size: 36rpx;
	color: #999999;
}

.add-btn {
	flex: 1;
	background: linear-gradient(90deg, var(--ui-BG-Main), var(--ui-BG-Main-gradient));
	border-radius: 80rpx;
	font-size: 30rpx;
	font-weight: 500;
	line-height: 80rpx;
	color: $white;
	position: relative;
	z-index: 1;
}

.number-waring {
	color: #ffffff;
	font-size: 35rpx;
	font-weight: 700;
}
</style>
